package com.yuchen.ishop.web.app.interceptor;

import com.yuchen.ishop.Gobals;
import com.yuchen.ishop.service.goods.GoodsRestClient;
import com.yuchen.ishop.vo.CookieUserInfo;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.utils.CookieUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Jack Q
 *         订单拦截
 */
public class OrderInterceptor implements HandlerInterceptor {

    private final static Logger LOG = Logger.getLogger(OrderInterceptor.class);

    @Autowired
    private GoodsRestClient goodsRestClient;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getServletPath();
        if (url.startsWith("/order/goOrder.htm")){
            if(StringUtils.isNotBlank(request.getParameter("goodsId"))){
                String goodsId = request.getParameter("goodsId");
                String cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID, request);
                if(StringUtils.isNotBlank(cart)){
                    String[] goodsIds = StringUtils.split(cart,",");
                    if(!ArrayUtils.contains(goodsIds, goodsId)){
                        StringBuilder cartSb = new StringBuilder();
                        cartSb.append(cart).append(",").append(goodsId);
                        cart = cartSb.toString();
                        CookieUtils.addCookie(Gobals.COOKIE_CART_ID,cartSb.toString(),CookieUtils.one_day,response);
                    }
                }else{
                    CookieUtils.addCookie(Gobals.COOKIE_CART_ID,goodsId,CookieUtils.one_day,response);
                }
            }
        }
        CookieUserInfo userInfo = BaseAction.cookie2UserInfo(request);
        if (userInfo == null || !userInfo.isState()) {
            response.sendRedirect(request.getContextPath() + "/goLogin.htm?returnUrl="+url);
            return false;
        }
        if (url.startsWith("/order/goOrder.htm")) {
            if(!"buyer".equals(userInfo.getRole())){
                response.sendRedirect(request.getContextPath() + "/error.htm?type=order");
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
